<template>
  <div class="batch-operations">
    <!-- 批量输入区域 -->
    <el-card class="input-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>批量操作</span>
          <div class="header-actions">
            <el-upload
              :show-file-list="false"
              :before-upload="handleFileUpload"
              accept=".txt,.csv"
            >
              <el-button size="small">
                <el-icon><Upload /></el-icon>
                上传文件
              </el-button>
            </el-upload>
            <el-button size="small" @click="clearInput">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="input-section">
        <div class="input-controls">
          <el-radio-group v-model="operationType" @change="handleOperationChange">
            <el-radio label="get">批量获取</el-radio>
            <el-radio label="create">批量创建</el-radio>
            <el-radio label="delete">批量删除</el-radio>
          </el-radio-group>
          
          <div class="input-options">
            <el-checkbox v-model="useAsync">使用异步处理</el-checkbox>
            <el-input-number
              v-model="batchSize"
              :min="1"
              :max="1000"
              size="small"
              style="width: 120px; margin-left: 10px"
            />
            <span style="margin-left: 5px">条/批次</span>
          </div>
        </div>
        
        <div class="input-area">
          <el-input
            v-model="batchInput"
            type="textarea"
            :placeholder="inputPlaceholder"
            :rows="10"
            resize="vertical"
          />
          <div class="input-stats">
            <span>总行数: {{ inputLines.length }}</span>
            <span>有效Key数: {{ validKeys.length }}</span>
            <span>预计批次: {{ estimatedBatches }}</span>
          </div>
        </div>
      </div>
      
      <div class="action-buttons">
        <el-button
          type="primary"
          :loading="processing"
          :disabled="validKeys.length === 0"
          @click="executeBatchOperation"
        >
          <el-icon><Operation /></el-icon>
          执行批量操作
        </el-button>
        
        <el-button @click="showPreview = !showPreview">
          <el-icon><View /></el-icon>
          {{ showPreview ? '隐藏' : '显示' }}预览
        </el-button>
      </div>
    </el-card>

    <!-- 预览区域 -->
    <el-card v-show="showPreview" class="preview-card" shadow="never">
      <template #header>数据预览</template>
      <div class="preview-content">
        <el-table
          :data="previewData"
          style="width: 100%"
          max-height="300"
          size="small"
        >
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="key" label="Key" show-overflow-tooltip />
          <el-table-column prop="value" label="Value" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 进度区域 -->
    <el-card v-show="processing || results.length > 0" class="progress-card" shadow="never">
      <template #header>执行进度</template>
      <div class="progress-content">
        <div v-if="processing" class="progress-info">
          <el-progress
            :percentage="progressPercentage"
            :status="progressStatus"
            :stroke-width="20"
          />
          <div class="progress-details">
            <span>处理进度: {{ processedCount }}/{{ totalCount }}</span>
            <span>成功: {{ successCount }}</span>
            <span>失败: {{ errorCount }}</span>
            <span>耗时: {{ elapsedTime }}秒</span>
          </div>
        </div>
        
        <div v-if="results.length > 0" class="results-summary">
          <el-descriptions :column="4" size="small" border>
            <el-descriptions-item label="总计">{{ results.length }}</el-descriptions-item>
            <el-descriptions-item label="成功">
              <el-tag type="success" size="small">{{ successCount }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="失败">
              <el-tag type="danger" size="small">{{ errorCount }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="耗时">{{ totalElapsedTime }}秒</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 结果区域 -->
    <el-card v-show="results.length > 0" class="results-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>执行结果</span>
          <div class="header-actions">
            <el-button size="small" @click="exportResults">
              <el-icon><Download /></el-icon>
              导出结果
            </el-button>
            <el-button size="small" @click="clearResults">
              <el-icon><Delete /></el-icon>
              清空结果
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="results-content">
        <el-table
          :data="paginatedResults"
          style="width: 100%"
          v-loading="processing"
        >
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="key" label="Key" width="200" show-overflow-tooltip />
          <el-table-column prop="id" label="ID" width="120">
            <template #default="{ row }">
              <el-tag v-if="row.id" type="primary" size="small">{{ row.id }}</el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="Value" min-width="200" show-overflow-tooltip />
          <el-table-column prop="existed" label="状态" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.error" type="danger" size="small">失败</el-tag>
              <el-tag v-else-if="row.existed" type="success" size="small">已存在</el-tag>
              <el-tag v-else type="warning" size="small">新建</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="error" label="错误信息" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.error" class="error-text">{{ row.error }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="results.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
// 导入KV store和系统store
import { useKvStore, useSystemStore } from '../../store/pinia_stores.js'

// 初始化stores
const kvStore = useKvStore()
const systemStore = useSystemStore()

// 响应式数据
const operationType = ref('get')
const batchInput = ref('')
const batchSize = ref(100)
const useAsync = ref(true)
const processing = ref(false)
const showPreview = ref(false)

// 进度相关
const processedCount = ref(0)
const totalCount = ref(0)
const successCount = ref(0)
const errorCount = ref(0)
const startTime = ref(0)
const elapsedTime = ref(0)
const totalElapsedTime = ref(0)

// 结果相关
const results = ref([])
const currentPage = ref(1)
const pageSize = ref(20)

let progressTimer = null

// 计算属性
const inputLines = computed(() => {
  return batchInput.value.split('\n').filter(line => line.trim())
})

const validKeys = computed(() => {
  return inputLines.value
    .map(line => {
      const parts = line.trim().split('\t')
      return {
        key: parts[0],
        value: parts[1] || ''
      }
    })
    .filter(item => item.key)
})

const estimatedBatches = computed(() => {
  return Math.ceil(validKeys.value.length / batchSize.value)
})

const previewData = computed(() => {
  return validKeys.value.slice(0, 10).map(item => ({
    key: item.key,
    value: item.value || '(空)',
    status: '待处理'
  }))
})

const paginatedResults = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return results.value.slice(start, end)
})

const progressPercentage = computed(() => {
  if (totalCount.value === 0) return 0
  return Math.round((processedCount.value / totalCount.value) * 100)
})

const progressStatus = computed(() => {
  if (processing.value) return 
  return errorCount.value > 0 ? 'exception' : 'success'
})

const inputPlaceholder = computed(() => {
  switch (operationType.value) {
    case 'get':
      return '输入要获取的Key列表，每行一个：\nkey1\nkey2\nkey3'
    case 'create':
      return '输入要创建的KV对，每行一个，格式：Key[Tab]Value\nkey1\tvalue1\nkey2\tvalue2'
    case 'delete':
      return '输入要删除的Key列表，每行一个：\nkey1\nkey2\nkey3'
    default:
      return '请选择操作类型'
  }
})

// 监听器
watch(processing, (newVal) => {
  if (newVal) {
    startProgressTimer()
  } else {
    stopProgressTimer()
  }
})

// 方法
const handleOperationChange = () => {
  batchInput.value = ''
  showPreview.value = false
}

const handleFileUpload = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    batchInput.value = e.target.result
    ElMessage.success('文件上传成功')
  }
  reader.readAsText(file)
  return false // 阻止自动上传
}

const clearInput = () => {
  batchInput.value = ''
  showPreview.value = false
}

const executeBatchOperation = async () => {
  if (validKeys.value.length === 0) {
    ElMessage.warning('请输入有效的数据')
    return
  }

  processing.value = true
  results.value = []
  processedCount.value = 0
  successCount.value = 0
  errorCount.value = 0
  totalCount.value = validKeys.value.length
  startTime.value = Date.now()

  try {
    switch (operationType.value) {
      case 'get':
      case 'create':
        await executeBatchGetOrCreate()
        break
      case 'delete':
        await executeBatchDelete()
        break
    }
  } catch (error) {
    ElMessage.error('批量操作失败: ' + error.message)
  } finally {
    processing.value = false
    totalElapsedTime.value = Math.round((Date.now() - startTime.value) / 1000)
  }
}

const executeBatchGetOrCreate = async () => {
  const keys = validKeys.value.map(item => item.key)
  
  if (useAsync.value) {
    // 异步批量处理
    const response = await kvStore.batchGetOrCreate(keys)
    results.value = response.results.map(item => ({ ...item, error: null }))
    
    if (response.errors && response.errors.length > 0) {
      response.errors.forEach(error => {
        results.value.push({ key: 'ERROR', error, existed: false })
      })
    }
    
    successCount.value = response.results.length
    errorCount.value = response.errors ? response.errors.length : 0
    processedCount.value = totalCount.value
  } else {
    // 同步分批处理
    const batches = []
    for (let i = 0; i < keys.length; i += batchSize.value) {
      batches.push(keys.slice(i, i + batchSize.value))
    }

    for (const batch of batches) {
      try {
        const response = await kvStore.batchGetOrCreate(batch)
        results.value.push(...response.results.map(item => ({ ...item, error: null })))
        successCount.value += response.results.length
        
        if (response.errors && response.errors.length > 0) {
          errorCount.value += response.errors.length
        }
      } catch (error) {
        errorCount.value += batch.length
        batch.forEach(key => {
          results.value.push({ key, error: error.message, existed: false })
        })
      }
      
      processedCount.value = Math.min(processedCount.value + batch.length, totalCount.value)
    }
  }
}

const executeBatchDelete = async () => {
  const keys = validKeys.value.map(item => item.key)
  
  for (const key of keys) {
    try {
      const success = await kvStore.deleteKv(key)
      results.value.push({
        key,
        id: null,
        value: null,
        existed: success,
        error: success ? null : '删除失败'
      })
      
      if (success) {
        successCount.value++
      } else {
        errorCount.value++
      }
    } catch (error) {
      results.value.push({
        key,
        id: null,
        value: null,
        existed: false,
        error: error.message
      })
      errorCount.value++
    }
    
    processedCount.value++
  }
}

const startProgressTimer = () => {
  progressTimer = setInterval(() => {
    elapsedTime.value = Math.round((Date.now() - startTime.value) / 1000)
  }, 1000)
}

const stopProgressTimer = () => {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
}

const clearResults = () => {
  results.value = []
  processedCount.value = 0
  successCount.value = 0
  errorCount.value = 0
  currentPage.value = 1
}

const exportResults = () => {
  const csvContent = ['Key,ID,Value,Status,Error']
    .concat(results.value.map(row => 
      `"${row.key}","${row.id || ''}","${row.value || ''}","${row.error ? '失败' : (row.existed ? '已存在' : '新建')}","${row.error || ''}"`
    ))
    .join('\n')
    
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `batch_results_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`
  link.click()
}

const getStatusTagType = (status) => {
  switch (status) {
    case '待处理': return 'info'
    case '成功': return 'success'
    case '失败': return 'danger'
    default: return 'info'
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}
</script>

<style scoped>
.batch-operations {
  padding: 0;
}

.input-card,
.preview-card,
.progress-card,
.results-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.input-section {
  margin-bottom: 20px;
}

.input-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.input-options {
  display: flex;
  align-items: center;
}

.input-area {
  position: relative;
}

.input-stats {
  display: flex;
  gap: 20px;
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.progress-content {
  padding: 10px 0;
}

.progress-info {
  margin-bottom: 20px;
}

.progress-details {
  display: flex;
  gap: 20px;
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}

.results-summary {
  margin-top: 20px;
}

.error-text {
  color: #f56c6c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>